/*
 * Copyright 2014 Graham Smith
 */
package uk.co.wobblycogs.vegas.scan;

import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.eclipse.persistence.queries.CursoredStream;
import uk.co.wobblycogs.vegas.AbstractService;
import uk.co.wobblycogs.vegas.VegasUtilities;

/**
 *
 * @author Graham Smith
 */
public class FileResourceService extends AbstractService<FileResource> {

	public FileResourceService() {
	}

	@Override
	public FileResource find(Long id) {
		EntityManager em = emf.createEntityManager();
		return em.find(FileResource.class, id);
	}

	public CursoredStream findAll() {
		EntityManager em = emf.createEntityManager();
		Query q = em.createNamedQuery(FileResource.FIND_ALL);
		//Tell the EntityManager to return a StreamedCursor
		q.setHint("eclipselink.cursor", true);
		return (CursoredStream) q.getSingleResult();
	}

	public FileResource findByPath(Path path) {
		EntityManager em = emf.createEntityManager();
		TypedQuery<FileResource> query = em.createNamedQuery(FileResource.FIND_BY_PATH, FileResource.class);
		query.setParameter("resourcePath", path);
		List<FileResource> results = query.getResultList();
		FileResource f = null;
		if (results != null && !results.isEmpty()) {
			f = results.get(0);
		}

		return f;
	}

	public void removeMissingMedia() {
		Instant start = Instant.now();

		List<FileResource> missing = new ArrayList<>();
		CursoredStream cursor = findAll();
		while (!cursor.atEnd()) {
			FileResource r = (FileResource) cursor.next();
			missing.add(r);
		}

		missing.stream().forEach((r) -> {
			remove(r);
		});

		Instant end = Instant.now();
		logger.debug("Missing media removal time: {}", VegasUtilities.formatDuration(start, end));
	}

}
